package org.chen.hotel.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.chen.common.hotel.City;
import org.chen.common.hotel.vo.CityVO;
import org.chen.hotel.mapper.CityMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CityService {
    
    @Autowired
    private CityMapper cityMapper;
    
    /**
     * 获取所有启用的城市，按排序值排序
     */
    public List<CityVO> getAllActiveCities() {
        QueryWrapper<City> wrapper = new QueryWrapper<>();
        wrapper.eq("is_active", 1)
               .orderByAsc("sort_order")
               .orderByDesc("create_time");
        
        List<City> cities = cityMapper.selectList(wrapper);
        return cities.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }
    
    /**
     * 根据国家ID获取城市列表
     */
    public List<CityVO> getCitiesByCountryId(Integer countryId) {
        QueryWrapper<City> wrapper = new QueryWrapper<>();
        wrapper.eq("country_id", countryId)
               .eq("is_active", 1)
               .orderByAsc("sort_order")
               .orderByDesc("create_time");
        
        List<City> cities = cityMapper.selectList(wrapper);
        return cities.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }
    
    /**
     * 根据城市代码获取城市信息
     */
    public CityVO getCityByCode(String code) {
        QueryWrapper<City> wrapper = new QueryWrapper<>();
        wrapper.eq("code", code)
               .eq("is_active", 1);
        
        City city = cityMapper.selectOne(wrapper);
        return city != null ? convertToVO(city) : null;
    }
    
    /**
     * 根据ID获取城市信息
     */
    public CityVO getCityById(Integer id) {
        City city = cityMapper.selectById(id);
        return city != null ? convertToVO(city) : null;
    }
    
    /**
     * 转换为VO
     */
    private CityVO convertToVO(City city) {
        CityVO vo = new CityVO();
        vo.setId(city.getId());
        vo.setName(city.getName());
        vo.setEnglishName(city.getEnglishName());
        vo.setCountryId(city.getCountryId());
        vo.setCityId(city.getCityId());
        vo.setCountryName(city.getCountryName());
        vo.setCode(city.getCode());
        return vo;
    }
}